#include "SDL.h"

void quit (int rc) {
  SDL_Quit();
  exit(rc);
}

int main (int argc, char** argv) {
  SDL_Window* window;
  SDL_Renderer* renderer;
  SDL_Surface* ballSurf;
  SDL_Texture* ball;
  Uint16 ballX, ballY;
  Sint8 dx, dy;
  Uint16 ballW, ballH;
  SDL_Event evt;
  SDL_bool done = SDL_FALSE;

  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
    exit(1);
  }

  if (!(ballSurf = SDL_LoadBMP("life.bmp"))) {
    fprintf(stderr, "Couldn't load image : life.bmp\n");
    quit(2);
  }

  window = SDL_CreateWindow("Test bounce SDL 1.3",
                            SDL_WINDOWPOS_UNDEFINED,
                            SDL_WINDOWPOS_UNDEFINED,
                            1024, 768,
                            SDL_WINDOW_SHOWN|SDL_WINDOW_FULLSCREEN);

  if (!window) {
    fprintf(stderr, "Couldn't set create window: %s\n", SDL_GetError());
    quit(3);
  }

  renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
  if (!renderer) {
    fprintf(stderr, "Couldn't set create renderer: %s\n", SDL_GetError());
    quit(4);
  }

  if (!(ball = SDL_CreateTextureFromSurface(renderer, ballSurf))) {
    SDL_FreeSurface(ballSurf);
    quit(5);
  }

  ballW = ballSurf->w;
  ballH = ballSurf->h;

  // Not needed anymore.
  SDL_FreeSurface(ballSurf);

  ballX = 512;
  ballY = 384;
  
  dx = -1;
  dy = -1;
  
  SDL_Rect dst = { -1, -1, ballW, ballH };

  while (!done) {
    while (SDL_PollEvent(&evt)) {
      switch (evt.type) {
        case SDL_QUIT:
          done = SDL_TRUE;
          break;
        case SDL_KEYDOWN:
          if (evt.key.keysym.sym == SDLK_ESCAPE) {
            done = SDL_TRUE;
          }
          break;
      }
    }

    // Render the ball at its current position.
    SDL_RenderClear(renderer);
    dst.x = ballX;
    dst.y = ballY;
    SDL_RenderCopy(renderer, ball, NULL, &dst);
    SDL_RenderPresent(renderer);

    // Move the ball and bounce if necessary.
    ballX += dx;
    ballY += dy;

    if ((ballX <= 0) || (ballX + ballW >= 1024)) {
      dx = -dx;
    }

    if ((ballY <= 0) || (ballY + ballH >= 768)) {
      dy = -dy;
    }

    //SDL_Delay(0);
  }

  SDL_DestroyTexture(ball);
  SDL_DestroyRenderer(renderer);

  quit(0);
  return 0;
}

